using Castle.Components.DictionaryAdapter;
using Castle.MonoRail.Framework;
using KenEgozi.Com.Weblog.Filters;
using KenEgozi.Com.Weblog.Interfaces;
using KenEgozi.Com.Weblog.Services;

namespace KenEgozi.Com.Weblog.Controllers
{
	[Filter(ExecuteEnum.BeforeAction, typeof(AdminOnlyFilter))]
	public class AdminController : AbstractController
	{
		readonly ISecurityService securityService;

		ILoginView typedPropertyBag = null;
		IBasicView typedFlash = null;

		public AdminController(ISecurityService securityService, IDictionaryAdapterFactory dictionaryAdapterFactory, ICachedItemsService cachedItemsService)
			:base(cachedItemsService, dictionaryAdapterFactory)
		{
			this.securityService = securityService;
		}

		protected override void SetGoogleAnalyticsParameter()
		{
			LayoutBag.ShowGoogleAnalytics = false;
		}

		private ILoginView TypedPropertyBag
		{
			get
			{
				if (typedPropertyBag == null)
					typedPropertyBag =
						DictionaryAdapterFactory.GetAdapter<ILoginView>(PropertyBag);
				return typedPropertyBag;
			}
		}

		private IBasicView TypedFlash
		{
			get
			{
				if (typedFlash == null)
					typedFlash =
						DictionaryAdapterFactory.GetAdapter<IBasicView>(Flash);
				return typedFlash;
			}
		}

		public void Login(string returnUrl)
		{
			SetLayoutParameters();
			TypedPropertyBag.ReturnUrl = returnUrl;
		}

		public void Login(string username, string password, string returnUrl)
		{
			if (securityService.IsAuthenticated(username, password) == false)
			{
				TypedFlash.ErrorMessage = "Wrong credentials";
				Redirect("admin", "login");
			}

			Session["IsAdmin"] = true;

			if (string.IsNullOrEmpty(returnUrl))
				Redirect("admin", "index");
			else 
				Redirect(returnUrl);
		}

		public void index()
		{
			SetLayoutParameters();
		}

		public void ChangePassword()
		{
			SetLayoutParameters();
		}

		public void ChangePassword(string newPassword)
		{
			securityService.SetAdminPassword(newPassword);
			Redirect("admin", "index");
		}
	}
}